const express = require("express")//引入express
const multer = require("multer")//上传文件中间件
const path = require("path")
const { db, genid } = require("./db/DbUtils")
const app = express()//实例化
const port = 3000

//开放跨域请求
app.use(function (req, res, next) {
  //设置允许跨域的域名，*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin", "*");
  //允许的header类型,允许全部头
  res.header("Access-Control-Allow-Headers", "*");
  //跨域允许的请求方式
  res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
  if (req.method == "OPTIONS") res.sendStatus(200); //让options尝试请求快速结束
  else next();
});


app.use(express.json())//写中间件,而且要尽可能往上写
const update = multer({
  dest: "./public/upload/temp"//制定临时存放路径
})
app.use(update.any())//允许所有接口都有上传功能
app.use(express.static(path.join(__dirname, "public")))//访问静态文件

//category/_token/add
const ADMIN_TOKEN_PATH = "/_token"
app.all("*", async (req, res, next) => {
  if (req.path.indexOf(ADMIN_TOKEN_PATH) > -1) {

    let { token } = req.headers//添加token

    let admin_token_sql = " select * from `admin` where `token` = ? "
    let adminResult = await db.async.all(admin_token_sql, [token])
    if (adminResult.err != null || adminResult.rows.length == 0) {
      res.send({
        code: 403,
        msg: "请先登录"
      })
      return
    } else {
      next()
    }

  } else {
    next()
  }
})

app.use("/test", require("./routers/TestRouter"))
app.use("/admin", require("./routers/AdminRouter"))
app.use("/category", require("./routers/CategoryRouter"))
app.use("/blog", require("./routers/BlogRouter"))
app.use("/upload", require("./routers/UploadRouter"))
//路由往后写
app.get("/", (req, res) => {
  res.send("hello,world")
})

app.listen(port, () => {
  console.log(`启动成功:http://localhost:${port}`)
})